package com.begye.smartloan.apptest.detailadsource

import android.annotation.SuppressLint
import android.graphics.Color
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.ImageView
import android.widget.RelativeLayout
import android.widget.TextView
import androidx.recyclerview.widget.RecyclerView
import com.begye.smartloan.apptest.R
import org.json.JSONObject

class DetailAfterDayAdapter(var dataList: List<JSONObject>, var onClickAction: (Int) -> Unit) :
    RecyclerView.Adapter<DetailAfterDayAdapter.ViewHolder>() {

    override fun onCreateViewHolder(
        parent: ViewGroup,
        viewType: Int,
    ): ViewHolder {
        val view = LayoutInflater.from(parent.context)
            .inflate(R.layout.list_item_detail_day, parent, false)

//        val layoutParams = view.layoutParams
//        layoutParams.width = parent.width / 3
//        view.layoutParams = layoutParams

        return ViewHolder(view)
    }

    inner class ViewHolder(view: View) : RecyclerView.ViewHolder(view) {
        private val listItemDetailDayBg: RelativeLayout =
            view.findViewById(R.id.listItemDetailDayBg)

        private val listItemDetailDayValue: TextView =
            view.findViewById(R.id.listItemDetailDayValue)

        private val listItemDetailDayCheckBox: ImageView =
            view.findViewById(R.id.listItemDetailDayCheckBox)


        fun bindData(position: Int, item: JSONObject) {

            listItemDetailDayValue.text = item.optString("day")

            val isChecked = item.optBoolean("isChecked", false)
            if (isChecked) {
                listItemDetailDayValue.setTextColor(Color.parseColor("#BEFF6A"))
                listItemDetailDayValue.setBackgroundResource(R.drawable.layer_c25_000000)

                listItemDetailDayCheckBox.visibility = View.VISIBLE

            } else {
                listItemDetailDayValue.setBackgroundResource(R.drawable.layer_c25_000000_stroke)
                listItemDetailDayValue.setTextColor(Color.parseColor("#000000"))

                listItemDetailDayCheckBox.visibility = View.INVISIBLE
            }

            listItemDetailDayBg.setOnClickListener {
                for (index in dataList.indices) {
                    val obj = dataList[index]
                    obj.put("isChecked", index == position)
                }
                onClickAction.invoke(position)
            }
        }
    }

    @SuppressLint("SetTextI18n")
    override fun onBindViewHolder(holder: ViewHolder, position: Int) {
        holder.bindData(position, dataList[position])
    }

    override fun getItemCount(): Int {
        return dataList.size
    }
}